package com.lindroy.androidplayer.base.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.RecyclerView
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.databinding.FooterNoMoreDataBinding
import com.lindroy.androidplayer.databinding.FooterReloadBinding

/**
 * @author Lin
 * @date 2022/1/22
 * @function
 */

private const val FOOTER_RELOAD = 0x00
private const val FOOTER_NO_MORE_DATA = 0x01

class FooterAdapter(private val listener: (() -> Unit)?) :
    LoadStateAdapter< RecyclerView.ViewHolder>() {

    class NoMoreDataViewHolder(val binding: FooterNoMoreDataBinding) : RecyclerView.ViewHolder(binding.root)
    class ReloadViewHolder(val binding: FooterReloadBinding) : RecyclerView.ViewHolder(binding.root)

    override fun getStateViewType(loadState: LoadState) = if (loadState is LoadState.Error) {
        FOOTER_RELOAD
    } else FOOTER_NO_MORE_DATA


    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, loadState: LoadState) {
        if (holder is ReloadViewHolder){
            holder.binding.apply {
                loadingView.isVisible = loadState is LoadState.Loading
                tvReload.isVisible = loadState is LoadState.Error
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState) =
        when (getStateViewType(loadState)) {
            FOOTER_NO_MORE_DATA -> NoMoreDataViewHolder(
                DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context),
                    R.layout.footer_no_more_data,
                    parent,
                    false
                )
            )
            else -> ReloadViewHolder(
                DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context),
                    R.layout.footer_reload,
                    parent,
                    false
                )
            ).apply {
                binding.tvReload.setOnClickListener {
                    listener?.invoke()
                }
            }
        }

    override fun displayLoadStateAsItem(loadState: LoadState) =
        when(getStateViewType(loadState)){
            FOOTER_NO_MORE_DATA-> loadState is LoadState.NotLoading && loadState.endOfPaginationReached
            else -> super.displayLoadStateAsItem(loadState)
        }

}